﻿using System;
using System.Collections.Generic;
using System.Text;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;
using Kugar.Core.Web;

namespace Kugar.Tool.Web.RequestFieldValidation.Rules
{
    public class EqualToFieldRule<TInputValue> : RuleBase where TInputValue:IComparable
    {
        internal EqualToFieldRule(string compareFieldName,string compareFieldTitle,string errorMsg):base(errorMsg)
        {
            EqualToFieldName = compareFieldName;
            EqualToFieldTitle = compareFieldTitle;
        }

        public string EqualToFieldName { get; }

        public string EqualToFieldTitle { get; }

        //public override string DefaultErrorMessage
        //{
        //    get { return $"必须与{EqualToFieldTitle}相等"; }
        //}

        protected override string BuildDefaultErrorMessage(IRequestField field)
        {
            return $"{field.Title}必须与{EqualToFieldTitle}相等";
        }

        protected override bool ValidateField(IRequestField field)
        {
            var compareValue = field.Request.GetString(EqualToFieldName);

            var cv= RequestFieldServices.ConvertTo<TInputValue>(compareValue, field.Format, default(TInputValue));

            return ((IRequestField<TInputValue>) field).Value().CompareTo(cv)==0;
            
        }
    }

    public class EqualToFieldRuleNullable<TInputValue> : RuleBase where TInputValue : struct 
    {
        internal EqualToFieldRuleNullable(string compareFieldName, string compareFieldTitle, string errorMsg) : base(errorMsg)
        {
            EqualToFieldName = compareFieldName;
            EqualToFieldTitle = compareFieldTitle;
        }

        public string EqualToFieldName { get; }

        public string EqualToFieldTitle { get; }

        //public override string DefaultErrorMessage
        //{
        //    get { return $"必须与{EqualToFieldTitle}相等"; }
        //}

        protected override string BuildDefaultErrorMessage(IRequestField field)
        {
            return $"{field.Title}必须与{EqualToFieldTitle}相等";
        }

        protected override bool ValidateField(IRequestField field)
        {
            var compareValue = field.Request.GetString(EqualToFieldName);

            var cv = RequestFieldServices.ConvertTo<TInputValue?>(compareValue, field.Format, default(TInputValue?));

            var v = ((IRequestField<TInputValue?>) field).Value();

            return  Nullable.Compare(cv,v) == 0;

        }
    }
}
